package com.dal.myconsul.controller;

import com.dal.myconsul.domain.ServiceInfo;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class DiscoveryController {
    @Resource
    RedisTemplate redisTemplate;

    /**
     * 注册服务
     * @return
     */
    @GetMapping ("/registerService")
    public String registerService(@RequestParam() String name, @RequestParam() String ip, @RequestParam(defaultValue = "80") int port){

        ListOperations<String, ServiceInfo> listOps = redisTemplate.opsForList();
        var key="services_"+name;
        // 取出所有服务
        List<ServiceInfo> serviceInfos = listOps.range(key, 0, -1);
        var serviceInfo =new ServiceInfo(name,ip,port);
        // 判断服务是否已经注册
        int size = serviceInfos
                .stream()
                .filter(info -> info.equals(serviceInfo))
                .collect(Collectors.toList())
                .size();
        // size为零则将参数传进来的服务注册到redis
        if (size == 0){
            listOps.leftPush(key, serviceInfo);
            return "服务已进行注册";
        } else {
            return "服务已经存在，无需重复注册";
        }
    }
}
